package concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 生产者消费者模型
 */
public class ProducerConsumer {
    private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5); // 阻塞队列大小为5

    private static class Producer extends Thread{
        @Override
        public void run(){
            try {
                System.out.println("produce...");
                queue.put("product"); // 先生成，生产完了放到队列中
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
    private static class Consumer extends Thread{
        @Override
        public void run(){
            try {
                String product = queue.take(); // 同步队列中能够拿到，才进行消费
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("consume..");
        }
    }

    public static void main(String[] args) {
        // 2个生产者线程
        for (int i = 0; i < 2; i++) {
            Producer producer = new Producer();
            producer.start();
        }
        for (int i = 0; i < 5; i++) {
            Consumer consumer = new Consumer();
            consumer.start();
        }
        for (int i = 0; i < 3; i++) {
            Producer producer = new Producer();
            producer.start();
        }
    }
}
